const express=require('express')
const fs=require('fs')
const path=require('path')
const userrouter=express.Router()

//分页查询接口
userrouter.get('/xuan',(req,res)=>{
   const {current,count}=req.query
    var lujing=path.join(__dirname,'../json/user.json')
    var shuzu= fs.readFileSync(lujing).toString() ? JSON.parse(fs.readFileSync(lujing).toString()) : []
   var newshuzu=shuzu.slice((current-1)*count,current*count)
    res.send({code:200,list:newshuzu,total:shuzu.length})
}) 
// 模糊查询
userrouter.get('/cha',(req,res)=>{
    const {gjc}=req.query
     var lujing=path.join(__dirname,'../json/user.json')
     var shuzu= fs.readFileSync(lujing).toString() ? JSON.parse(fs.readFileSync(lujing).toString()) : []
   var newshuzu=shuzu.filter((item)=>{
        return item.name.indexOf(gjc) != -1
    })
     res.send({code:200,list:newshuzu,total:shuzu.length})
 }) 
// 用户登录
userrouter.post('/login',(req,res)=>{
    const {phone,mima}=req.body
     var lujing=path.join(__dirname,'../json/user.json')
     var shuzu= fs.readFileSync(lujing).toString() ? JSON.parse(fs.readFileSync(lujing).toString()) : []
   var i= shuzu.findIndex((item)=>{
        return item.phone==phone && item.mima==mima;
    })
   
    if(i != -1){

        res.send({code:200,msg:'登陆成功!',userinfo: shuzu[i], token:''})

    }else{
        res.send({code:200,msg:'登陆失败!', token:''})

    }
 }) 
 // 用户注册
 userrouter.post('/register',(req,res)=>{
    const {name,phone,mima,email}=req.body
     var lujing=path.join(__dirname,'../json/user.json')
     var shuzu= fs.readFileSync(lujing).toString() ? JSON.parse(fs.readFileSync(lujing).toString()) : []
   var i= shuzu.findIndex((item)=>{
        return item.phone==phone;
    })
    
    if(i == -1){
        shuzu.push({  "email":email,"name":name,"phone":phone,"ingroup":"办公室","guanli":false,"zhuangtai":true,"mima":mima})
       fs.writeFileSync(lujing,JSON.stringify(shuzu),'utf8')
        res.send({code:200,msg:'注册成功', token:''})

    }else{
        res.send({code:200,msg:'登陆失败!', token:''})

    }
 }) 
 // 用户删除
 userrouter.post('/delete',(req,res)=>{
    const {phone}=req.body
     var lujing=path.join(__dirname,'../json/user.json')
     var shuzu= fs.readFileSync(lujing).toString() ? JSON.parse(fs.readFileSync(lujing).toString()) : []
   var i= shuzu.findIndex((item)=>{
        return item.phone==phone 
    })
   
    if(i != -1){

        shuzu.splice(i,1)
       let current=Math.ceil((i+1)/3)
        var newshuzu=shuzu.slice((current-1)*3,current*3)
        fs.writeFileSync(lujing,JSON.stringify(shuzu),'utf8')
         res.send({code:200,msg:'删除成功', token:'',list:newshuzu,total:shuzu.length})
 
    }else{
        res.send({code:200,msg:'登陆失败!', token:''})

    }
 }) 
module.exports=userrouter